<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <input type="hidden" v-model="id">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in list">
          <td>{{index+1}}</td>
          <td>{{item.uname}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    let flag = false
    const app = new Vue({
      el: '#app',
      data: {
        list: [{
          id: 1,
          uname: '张三',
          age: 28,
          gender: '男'
        }, {
          id: 2,
          uname: '李华',
          age: 14,
          gender: '男'
        }, {
          id: 3,
          uname: '小红',
          age: 19,
          gender: '女'
        }],
        name: '',
        age: '',
        sex: '男',
        id: ''
      },
      methods: {
        add() {
          if (!flag) {
            // 添加
            if (!this.name || !this.age || !this.sex) {
              alert('输入不能为空')
              return
            }
            this.list.push({
              id: Date.now(),
              uname: this.name,
              age: this.age,
              gender: this.sex
            })
            this.name = this.age = ''
          } else {
            // 编辑
            this.list.forEach(item => {
              if (item.id === this.id) {
                item.uname = this.name
                item.age = this.age
                item.gender = this.sex
              }
            })
            this.name = this.age = ''
            flag = false
          }
        },
        edit(id) {
          flag = true
          const obj = this.list.filter(item => item.id === id)
          console.log(obj)
          this.name = obj[0].uname
          this.age = obj[0].age
          this.sex = obj[0].gender
          this.id = obj[0].id
        },
        del(id) {
          console.log(id)
          this.list = this.list.filter(item => item.id !== id)
        }
      },
    })
  </script>
</body>

</html>